//
//  XianhuoDetailVC.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/8.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import Kingfisher

class XianhuoDetailVC: UIViewController , SliderGalleryControllerDelegate {

    let contentView = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    
    let banner = SliderGalleryPresenter()
    var bannerModels : [String] = []

    var model : XianhuoModel?
    var showStatus = false
    var shareView : UIView?
    var maskView : UIView?

    let SHARE_URL = "http://www.yunshutech.com/order.action#offer?id="
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = Const.WTM_WHITE_SMOKE
        self.contentView.backgroundColor = self.view.backgroundColor
        self.contentView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 64, right: 0)
        self.view.addSubview(self.contentView)
        
        self.setUpBanner()
        
        self.refreshUI()
        
        let btn = UIButton.init(type: .roundedRect)
        let btn2 = UIButton.init(type: .roundedRect)
    
        let whiteView = UIView.init(frame: CGRect.init(x: 0, y: Const.SCREEN_HEIGHT - 64, width: Const.SCREEN_WIDTH, height: 64))
        whiteView.backgroundColor = UIColor.white
        
        btn.backgroundColor = Const.WTM_GREEN
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.layer.cornerRadius = 5
        btn.addTarget(self, action: #selector(XianhuoDetailVC.dial), for: .touchUpInside)
        whiteView.addSubview(btn)
        btn.frame = CGRect.init(x: 10, y: 10, width: Const.SCREEN_WIDTH - 20, height: 44)
        btn.setTitle("拨打电话", for: .normal)
        if (model?.kucunpic) != nil {
            btn2.backgroundColor = Const.WTM_GREEN
            btn2.setTitleColor(UIColor.white, for: .normal)
            btn2.layer.cornerRadius = 5
            btn2.addTarget(self, action: #selector(XianhuoDetailVC.viewKCB), for: .touchUpInside)
            whiteView.addSubview(btn2)
            btn2.frame = CGRect.init(x: 20+(Const.SCREEN_WIDTH - 30)/2, y:10 , width: (Const.SCREEN_WIDTH - 30)/2, height: 44)
            btn2.setTitle("查看库存表", for: .normal)
            
            btn.frame = CGRect.init(x: 10, y: 10, width: (Const.SCREEN_WIDTH - 30)/2, height: 44)
        }
        
        self.view.addSubview(whiteView)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "分享", style: .plain, target: self, action: #selector(XianhuoDetailVC.shareAction))
    }

    func refreshUI(){
        if showStatus {
            self.addStatus()
        }
        self.addItem("编号", value: (model?.xianhuoId)!)
        self.addType()
        self.addLine()
        
        self.addItem("类别", value: (model?.channelname)!)
        self.addItem("生产厂家", value: (model?.factory)!)
        self.addItem("今日报价", value: (model?.price)!)
        self.addItem("材质", value: (model?.quality)!)
        self.addItem("规格", value: (model?.specification)!)
//        self.addItem("库存", value: model?.)
        self.addItem("货物所在地", value: (model?.storehouse)!)
        self.addLine()

        self.addItem("公司", value: (model?.company)!)
        self.addItem("联系人", value: (model?.contact)!)
        self.addItem("手机", value: (model?.tel)!)
        self.addItem("公司介绍", value: (model?.companymark)!)
        self.addItem("备注", value: (model?.mark)!)

    }
    
    func addStatus(){
        var name = ""
        let audit:String = (self.model?.audit)!
        switch audit{
        case "0" :
            name = "待审核"
        case "1" :
            name = "审核通过"
        case "2" :
            name = "审核拒绝"
        default: break
        }
        
        self.addItem(name, nameColor: UIColor.red, value: model?.auditdesc, valueColor: UIColor.red)
    }
    
    func addItem(_ name:String, nameColor:UIColor, value:String?, valueColor:UIColor) {
        let container = UIView.init()
        container.tag = 99
        let nameLabel = UILabel.init(frame: CGRect.init(x: 10, y: 10, width: 100, height: 30))
        nameLabel.text = name
        nameLabel.textColor = nameColor
        container.addSubview(nameLabel)
        
        var height : CGFloat = 50
        
        if let reason = value {
            let reasonLabel = UILabel.init()
            reasonLabel.text = value
            reasonLabel.textColor = valueColor
            reasonLabel.numberOfLines = 0
            let width = Const.SCREEN_WIDTH - 100 - 20
            let titleHeight = UIUtility.calcStringHeight(reason, font: reasonLabel.font, refWidth: width)
            reasonLabel.frame = CGRect.init(x: 110, y: 10, width: width, height: titleHeight + 4)
            container.addSubview(reasonLabel)
            if (titleHeight + 24) > height {
                height = titleHeight + 24
            }
        }
        
        container.frame = CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: height)
        container.backgroundColor = self.contentView.backgroundColor
        self.contentView.addSubview(container)
    }
    
    func addItem(_ name:String, value:String){
        self.addItem(name, nameColor: Const.WTM_GRAY, value: value, valueColor: UIColor.black)
    }
    
    func  addType() -> Void {
        let container = UIView.init()
        container.tag = 99
        let nameLabel = UILabel.init(frame: CGRect.init(x: 10, y: 10, width: 100, height: 30))
        nameLabel.text = model?.type == 0 ? "现货" : "采购"
        nameLabel.textColor = Const.WTM_GRAY
        container.addSubview(nameLabel)
        
        let locImageView = UIImageView.init(frame: CGRect.init(x: Const.SCREEN_WIDTH - 90, y: 16, width: 18, height: 18))
        locImageView.image = UIImage.init(named: "xh_location")
        container.addSubview(locImageView)

        let locLabel = UILabel.init(frame: CGRect.init(x: Const.SCREEN_WIDTH - 75, y: 10, width: 65, height: 30))
        locLabel.text = model?.place
        container.addSubview(locLabel)
        
        container.frame = CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: 50)
        container.backgroundColor = self.contentView.backgroundColor
        self.contentView.addSubview(container)

    }
    
    func addLine() -> Void {
        
        let line = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.ONE_PIXEL))
        line.tag = 99
        line.backgroundColor = Const.WTM_GRAY
        self.contentView.addSubview(line)

    }
    
    func setUpBanner() {
        self.banner.delegate = self
        if let pic = model?.productpic {
            self.bannerModels.append(pic)
        }
        if let pic = model?.productpic1 {
            self.bannerModels.append(pic)
        }
        if let pic = model?.productpic2 {
            self.bannerModels.append(pic)
        }
        if  self.bannerModels.count > 0 {
            self.banner.view.frame = CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH*0.428)
            self.banner.view.backgroundColor = Const.WTM_LIGHTGRAY
            self.banner.setupViews()
            self.banner.view.tag = 99
            self.contentView.addSubview(banner.view)
        }
        
    }
    
    // MARK:- banner delegate
    //获取数据源
    func galleryDataSource()->[String] {
        return self.bannerModels.map{
            $0
        }
    }
    //获取内部scrollerView的宽高尺寸
    func galleryScrollerViewSize()->CGSize {
        return CGSize.init(width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH * 0.432)
    }
    
    func galleryViewTapped(_ index:Int) {
        let vc:ImageViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
        vc.imageUrl = self.bannerModels[index]
        self.navigationController?.pushViewController(vc, animated: true)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        var y:CGFloat = 0
        for iView in contentView.subviews {
            if iView.tag == 99 {
                var frame = iView.frame
                frame.origin.y = y
                y += frame.size.height
                iView.frame = frame
            }
        }
        
        self.contentView.contentSize = CGSize.init(width: Const.SCREEN_WIDTH, height: y + 50)
    }
    
    @objc func dial() -> Void {
        let str="te@objc lprompt://" + (model?.tel)!
        // NSLog(@"str======%@",str);
        UIApplication.shared.openURL(URL.init(string: str)!)

    }
    
    @objc func viewKCB() {
        let vc:ImageViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
        vc.imageUrl = (model?.kucunpic)!
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func shareAction() {
        if let theView = self.shareView {
        } else {
            self.shareView = UIView.init(frame: CGRect.init(x: 0, y: Const.SCREEN_HEIGHT - 196, width: Const.SCREEN_WIDTH, height: 196))
            self.shareView?.backgroundColor = Const.WTM_WHITE_SMOKE
            let spacing = (Const.SCREEN_WIDTH - 50*3) / 4
            
            let timelineImg = UIImageView.init(frame: CGRect.init(x: spacing, y: 40, width: 50, height: 50))
            timelineImg.image = UIImage.init(named: "timeline2.png")
            timelineImg.tag = 1
            timelineImg.isUserInteractionEnabled = true
            self.shareView?.addSubview(timelineImg)

            let timeLabel = UILabel.init(frame: CGRect.init(x: spacing, y: 103, width: 50, height: 14))
            timeLabel.text = "朋友圈"
            timeLabel.font = UIFont.systemFont(ofSize: 13)
            timeLabel.textColor = Const.WTM_GRAY_FONT
            timeLabel.textAlignment = .center
            self.shareView?.addSubview(timeLabel)
            
            let sessionImg = UIImageView.init(frame: CGRect.init(x: spacing*2 + 50, y: 40, width: 50, height: 50))
            sessionImg.image = UIImage.init(named: "session2.png")
            sessionImg.isUserInteractionEnabled = true
            sessionImg.tag = 2
            self.shareView?.addSubview(sessionImg)
            let sessionLabel = UILabel.init(frame: CGRect.init(x: spacing*2 + 50, y: 103, width: 50, height: 14))
            sessionLabel.text = "微信"
            sessionLabel.font = UIFont.systemFont(ofSize: 13)
            sessionLabel.textColor = Const.WTM_GRAY_FONT
            sessionLabel.textAlignment = .center
            self.shareView?.addSubview(sessionLabel)
            
            let sinaImg = UIImageView.init(frame: CGRect.init(x: spacing*3 + 100, y: 40, width: 50, height: 50))
            sinaImg.image = UIImage.init(named: "weibo2.png")
            sinaImg.tag = 3
            sinaImg.isUserInteractionEnabled = true
            let sinaLabel = UILabel.init(frame: CGRect.init(x: spacing*3 + 100, y: 103, width: 50, height: 14))
            sinaLabel.text = "微博"
            sinaLabel.font = UIFont.systemFont(ofSize: 13)
            sinaLabel.textColor = Const.WTM_GRAY_FONT
            sinaLabel.textAlignment = .center
            self.shareView?.addSubview(sinaLabel)
            self.shareView?.addSubview(sinaImg)

            let tap = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap1 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            let tap2 = UITapGestureRecognizer.init(target: self, action: #selector(XianhuoDetailVC.onTapShare(_:)))
            timelineImg.addGestureRecognizer(tap)
            sessionImg.addGestureRecognizer(tap1)
            sinaImg.addGestureRecognizer(tap2)
            
            let btn = UIButton.init(frame: CGRect.init(x: 0, y: 147, width: Const.SCREEN_WIDTH, height: 49))
            btn.backgroundColor = UIColor.white
            btn.addTarget(self, action: #selector(XianhuoDetailVC.cancelShare(_:)), for: .touchUpInside)
            btn.setTitleColor(UIColor.black, for: .normal)
            btn.setTitle("取消", for: .normal)
            self.shareView?.addSubview(btn)
            
            maskView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
            maskView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
        }
        self.navigationController?.view.addSubview(maskView!)
        maskView?.addSubview(self.shareView!)
    }
    
    @objc func cancelShare(_ sender:UIView){
        maskView?.removeFromSuperview()
    }
    
    @objc func onTapShare(_ sender:UITapGestureRecognizer) {
        let senderView = sender.view
        if senderView?.tag == 1 {
            self.share2WX(WXSceneTimeline)
        }else if senderView?.tag == 2 {
            self.share2WX(WXSceneSession)
        }else if senderView?.tag == 3 {
            self.share2Weibo()
        }
    }
    
    func share2WX(_ scene: WXScene) {
        
        if !WXApi.isWXAppInstalled() {
            self.navigationController!.view.makeToast("请安装微信客户端")
            //            return;
        }
        
        guard let url = URL(string:(self.model?.kucunpic)!) else{
            let image = UIImage.init(named:"logo")
            self.doShare2WX(image!, scene:scene)
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            if error == nil {
                self.doShare2WX(image!, scene:scene)
                
            }else { //图片下载失败，默认图片
                //生成缩略图
                let image = UIImage.init(named:"logo")
                self.doShare2WX(image!, scene:scene)
            }
        }
        
        
    }
    
    func doShare2WX(_ image:UIImage ,scene: WXScene) {
        let ext = WXWebpageObject()
        ext.webpageUrl = SHARE_URL + (self.model?.xianhuoId)!
        
        let message = WXMediaMessage()
        message.title = self.model?.advert //(self.model?.channelname)! + "最新报价"
        message.description = self.model?.advert
        print("message.description:\(message.description)")
        message.mediaObject = ext
        message.mediaTagName = "MyPic"
        
        let req=SendMessageToWXReq()
        req.text=nil
        req.bText=false
        req.scene=Int32(scene.rawValue)
        
        let size = CGSize.init(width: 120, height: 120)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size ) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        message.thumbData=thumbImage!.jpegData(compressionQuality: 0.6)
        req.message=message
        let reuslt = WXApi.send(req)
        print("分享结果：\(reuslt)")
    }

    func share2Weibo() {
        if (!WeiboSDK.isWeiboAppInstalled()) {
            self.navigationController!.view.makeToast("请安装新浪微博客户端")
        }
        
        let version = WeiboSDK.version()
        print("WeiboSDK.version:\(version)")
        guard  let url = URL(string:(self.model?.kucunpic)!) else {
            let image = UIImage.init(named:"logo")
            self.share2WeiboWithImage(image!)
            return
        }
        
        KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL:url), options: .none, progressBlock: nil) { (image, error, cacheType, url) in
            if error == nil {
                self.share2WeiboWithImage(image!)
                
            }else { //图片下载失败，默认图片
                //生成缩略图
                let image = UIImage.init(named:"logo")
                self.share2WeiboWithImage(image!)
            }
        }
    }
    
    func share2WeiboWithImage(_ image:UIImage) {
        
        let webpageObject = WBWebpageObject()

        webpageObject.webpageUrl = SHARE_URL + (self.model?.xianhuoId)!
        webpageObject.objectID = ""
        webpageObject.title = (self.model?.channelname)! + "最新报价"
        
        let message = WBMessageObject()
        message.mediaObject = webpageObject
        message.text = self.model?.advert
        //            if text != nil {
        //                message.text = text!
        //            }
        
        let sendMessageToWeiboRequest = WBSendMessageToWeiboRequest()
        sendMessageToWeiboRequest.message = message
        
        let size = CGSize.init(width: 100, height: 100)
        
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        image.draw( in: CGRect.init(origin: CGPoint.zero, size: size) )
        let thumbImage=UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        webpageObject.thumbnailData = thumbImage!.jpegData(compressionQuality: 0.6)
        WeiboSDK.send(sendMessageToWeiboRequest)
    }

}
